<template>
    <div class="pagestyle">
        <div class="tabdiyBox" style="margin-bottom: 10px;">
            <span :style="{color:isDark?'rgba(255, 255, 255, 0.8)':''}"
                :class="state.topTabListType==item.label?'active':''" v-for="(item,index) in state.topTabList"
                :key="index" @click="topTabListClick(item)">{{ item.label }}</span>
        </div>
        <topbottomCom :optionsquery="1">
            <template v-slot:dragTopSlot>
                <list_controller @query="query" ref="zujianname" :options="state.options"
                    @cellClickEvent="cellClickEvent" :showCaozuo="state.showCaozuo">
                    <template v-slot:opraCurdBtnAll>
                        <span :class="
                      state.listBtnType == 1 ? 'listInfoBtn active' : 'listInfoBtn'
                    " @click="listInfoBtnClick(1)">
                            <svg-icon :class="state.listBtnType == 1 ? 'active' : ''" class-name="search-icon"
                                icon-class="qiehuan" />
                            实时{{state.topTabListType}}
                        </span>
                    </template>
                    <template v-slot:listSS="{ row, field }">
                        <div v-if="field == 'totalAccumulationTime'">
                            {{formatSecToStr(row.totalAccumulationTime*60)}}
                        </div>
                    </template>
                    <template v-slot:selectNamelist> 历史{{state.topTabListType}} </template>
                </list_controller>
            </template>
            <template v-slot:dragBottomSlot>
                <list_controller ref="zujiannametwo" :descQuery="state.descObj" :options="state.optionstwo" @pagechange="pagechange">
                    <template v-slot:opraCurdBtnlist="row">
                        <span>
                            <el-button class="tableFontSize" type="primary" link size="small"
                                @click="lookBtn(row.row.row)">填写分析
                            </el-button>
                            <el-button class="tableFontSize" type="primary" link size="small"
                                @click="editBtn(row.row.row)" v-if="row.row.row.templateDto != null">查看</el-button>
                        </span>
                    </template>
                    <template v-slot:listSS="{ row, field }">
                        <div v-if="field == 'accumulationTime'">
                            {{formatSecToStr(row.accumulationTime*60)}}
                        </div>
                    </template>
                    <template v-slot:selectNamelist> 详细信息(总计) </template>
                </list_controller>
            </template>
        </topbottomCom>
        <!-- 填写分析 -->
        <fillayaCom :fillayaComShow="state.fillayaComShow" @submitFormfillayaCom="submitFormfillayaCom"
            :tempList="state.tempList"></fillayaCom>
        <!-- 查看曲线 -->
        <chartCom :openChart="state.showChart" :data="state.chartData" @closeChart="closeChart">
        </chartCom>
        <!-- 查看分析 -->
        <ayadetailCom :detailsList="state.detailsList" :detailsShow="state.detailsShow"></ayadetailCom>
    </div>
</template>
<script setup>
    import topbottomCom from "./listCom/topbottomCom.vue";
    import list_controller from "@/components/commonCom/list_controller";
    import fillayaCom from "./listCom/fillayaCom.vue";
    import ayadetailCom from "./listCom/ayadetailCom.vue";
    import chartCom from "./listCom/chartCom.vue";
    import {
        computed,
        onMounted,
        reactive,
    } from "vue";
    import {
        table_headers
    } from "@/components/commonCom/table_headers";
    import axios from "@/utils/request";
    import usePagesStore from "@/store/modules/pages";
    import {
        ElMessage,
    } from "element-plus";
    import dayjs from "dayjs";
    import {
        searchareaTree
    } from "@/api/config";
    import useSettingsStore from '@/store/modules/settings'
    const settingsStore = useSettingsStore()
    const isDark = computed(() => settingsStore.isDark);
    const {
        proxy
    } = getCurrentInstance();
    const store = usePagesStore();
    const router = useRouter();
    let state = reactive({
        torealUrl: '/lb/lb_realZHAlarmList',
        topTabList: [{
                label: '组合报警',
                tableheads: 'hisAssortedCall',
                tableheadsT: 'hisAssortedCallDetail',
                dataUrl: '/HisAssortedCall/listHisAssortedCall',
                dataUrlT: '/HisAssortedCall/listHisAssortedCallDetail',
                modifyayaUrl: '/HisAssortedCall/modifyHisAssortedCall',
                assortedCallNamesUrl: '/HisAssortedCall/getHisAssortedCallNames',
                torealUrl: '/lb/lb_realZHAlarmList'
            }, {
                label: '组合断电',
                tableheads: 'hisAssortedBreak',
                tableheadsT: 'hisAssortedBreakDetail',
                dataUrl: '/hisAssortedBreak/listHisAssortedBreak',
                dataUrlT: '/hisAssortedBreak/listHisAssortedBreakDetail',
                modifyayaUrl: '/hisAssortedBreak/modifyHisAssortedBreak',
                assortedCallNamesUrl: '/hisAssortedBreak/getHisAssortedBreakNames',
                torealUrl: '/lb/lb_realZHCutList'
            },
            {
                label: '组合馈电异常',
                tableheads: 'hisAssortedFeed',
                tableheadsT: 'hisAssortedFeedDetail',
                dataUrl: '/hisAssortedFeed/listHisAssortedFeed',
                dataUrlT: '/hisAssortedFeed/listHisAssortedFeedDetail',
                modifyayaUrl: '/hisAssortedFeed/modifyHisAssortedFeed',
                assortedCallNamesUrl: '/hisAssortedFeed/getHisAssortedFeedNames',
                torealUrl: '/lb/lb_realZHFeedList'
            },
            {
                label: '组合累积计时',
                tableheads: 'hisAssortedAccumulation',
                tableheadsT: 'hisAssortedAccumulationDetail',
                dataUrl: '/hisAssortedAccumulation/list',
                dataUrlT: '/hisAssortedAccumulation/listDetails',
                modifyayaUrl: '/hisAssortedFeed/modifyHisAssortedAccumulation',
                assortedCallNamesUrl: '/merge/accumulation/getNames',
                torealUrl: '/lb/lb_realZHLJJSList'
            }
        ],
        modifyayaUrl: '/HisAssortedCall/modifyHisAssortedCall',
        detailsShow: false,
        detailsList: [],
        tempList: [],
        fillayaComShow: false, //控制填写分析抽屉显示
        listBtnType: undefined,
        options: {
            tableheads: computed(() => table_headers.hisAssortedCall), //模拟量
            listSS: [{
                field: "totalAccumulationTime"
            }],
            queryList: {
                autoSearch: router.currentRoute.value.query.label ? true : undefined,
                querys: [{
                        fieldsearch: "conditionType",
                        field: "conditionType",
                        title: "查询方式",
                        type: "radiospecial",
                        binddata: 1,
                        options: [{
                                label: "时间查询",
                                value: 1,
                            },
                            {
                                label: "班次查询",
                                value: 2,
                            },
                        ],
                        col: 4
                    },
                    {
                        field: ["startTime", "endTime"],
                        fieldsearch: ["startTime", "endTime"],
                        title: "时间范围",
                        col: 10,
                        type: "datetimestartEnd",
                        binddata: [dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'), dayjs().format(
                            'YYYY-MM-DD HH:mm:ss')],
                        typespecial: 2,
                        show: false,
                    },
                    {
                        field: "datetime",
                        fieldsearch: "datetime",
                        title: "日期",
                        type: "datetime",
                        binddata: dayjs().format('YYYY-MM-DD'),
                        typespecial: 1,
                        show: true,
                        col: 4
                    },
                    {
                        fieldsearch: "banci",
                        field: "banci",
                        title: "班次选择",
                        type: "selectspecial",
                        binddata: "",
                        options: [],
                        typespecial: 1,
                        show: true,
                    },
                    {
                        field: "assortedCallName",
                        typesub: 'zuheSpecial',
                        title: "组合名称",
                        type: "select",
                        binddata: "",
                        options: [],
                        col: 4
                    },
                    
                ],
            },
            dataUrl: "/HisAssortedCall/listHisAssortedCall",
        },
        optionstwo: {
            listSS: [{
                field: "accumulationTime"
            }],
            queryList: {
                detailListSear: true,
                autoSearch: true,
                querys: [],
            },
            tableheads: computed(() => table_headers.hisAssortedCallDetail), //模拟量详情
            dataUrl: "/HisAssortedCall/listHisAssortedCallDetail",
        },
        editId: undefined,
        banciList: [],
        showCaozuo: true,
        data: {},
        areaObj: {
            condition: 'A'
        },
        descObj: {},
        showChart: false,
        chartData: {},
        topTabListType: router.currentRoute.value.query.label ? router.currentRoute.value.query.label : '组合报警',
        assortedCallNamesUrl: '/HisAssortedCall/getHisAssortedCallNames'
    });
    // 顶部tab切换点击事件
    async function topTabListClick(item) {
        state.topTabListType = item.label
        state.options.tableheads = computed(() => table_headers[item.tableheads])
        state.optionstwo.tableheads = computed(() => table_headers[item.tableheadsT])
        state.options.dataUrl = item.dataUrl
        state.optionstwo.dataUrl = item.dataUrlT
        state.modifyayaUrl = item.modifyayaUrl
        state.assortedCallNamesUrl = item.assortedCallNamesUrl
        state.torealUrl = item.torealUrl
        proxy.$refs.zujianname.getData();
        let arr = await getassortedCallNamesUrl()
        state.options.queryList.querys.forEach(itemsub => {
            if (itemsub.typesub == 'zuheSpecial') {
                itemsub.binddata = undefined
                itemsub.options = arr
                if (item.label == '组合累积计时') {
                    itemsub.field = 'assortedAccumulationName'
                    itemsub.title = '组合累积计时名称'
                } else if (item.label == '组合报警') {
                    itemsub.field = 'assortedCallName'
                    itemsub.title = '组合名称'
                } else if (item.label == '组合断电') {
                    itemsub.field = 'assortedBreakName'
                    itemsub.title = '组合名称'
                } else if (item.label == '组合馈电异常') {
                    itemsub.field = 'assortedBreakName'
                    itemsub.title = '组合名称'
                }
            }
        })
    }
    // 填写分析抽屉
    function lookBtn(row) {
        state.editId = row.id;
        state.fillayaComShow = dayjs().unix();
    }
    // 提交填写分析
    function submitFormfillayaCom(data) {
        let dataObj = {};
        dataObj.id = state.editId;
        dataObj.templateDto = data;
        if (data) {
            axios.post(state.modifyayaUrl, dataObj).then((res) => {
                proxy.$modal.msgSuccess(res.msg);
                state.fillayaComShow = false;
                proxy.$refs.zujiannametwo.getData({
                    ...state.descObj
                });
            });
        } else {
            state.fillayaComShow = false;
        }
    }

    function listInfoBtnClick(type) {
        state.listBtnType = type;
        if (type == 1) {
            goPage();
        }
        if (type == 2) {
            if (store.records.length == 0 || store.records.length > 1) {
                ElMessage.error('请选择一个测点')
                state.listBtnType = undefined;
                return
            } else {
                state.showChart = !state.showChart
                state.chartData = {
                    pointIds: [store.records[0].pointId],
                    queryStartTime: store.records[0].cutStartTime,
                    queryEndTime: store.records[0].cutEndTime,
                }
            }
        }
    }
    // 编辑按钮
    function editBtn(row) {
        if (row.templateDto != null) {
            state.detailsShow = dayjs().unix();
        }
        state.detailsList = row.templateDto;
    }


    function cellClickEvent(row) {
        store.records=[]
        state.descObj.assortedCallName = row.assortedCallName
        state.descObj.assortedBreakName = row.assortedBreakName
        state.descObj.assortedAccumulationName = row.assortedAccumulationName
        proxy.$refs.zujiannametwo.getData({
            ...state.descObj
        });
    }

    function pagechange() {
        proxy.$refs.zujiannametwo.getData({
            ...state.descObj
        });
    }

    function formatSecToStr(seconds) {
        let daySec = 24 * 60 * 60;
        let hourSec = 60 * 60;
        let minuteSec = 60;
        let dd = Math.floor(seconds / daySec);
        let hh = Math.floor((seconds % daySec) / hourSec);
        let mm = Math.floor((seconds % hourSec) / minuteSec);
        let ss = seconds % minuteSec;
        if (dd > 0) {
            return dd + "天" + hh + "小时" + mm + "分钟" + ss + "秒";
        } else if (hh > 0) {
            return hh + "小时" + mm + "分钟" + ss + "秒";
        } else if (mm > 0) {
            return mm + "分钟" + ss + "秒";
        } else {
            return ss + "秒";
        }
    }

    function query(type) {
        if (type == 2) {
            proxy.$refs.zujiannametwo.state.tabledata = []
            getconditionList({})
            state.options.queryList.querys.forEach((item) => {
                if (item.field == "calibrationStatus") {
                    item.binddata = 3;
                }
            });
        }
        if (type.type == 4) {
            state.options.queryList.querys.forEach((item) => {
                if (item.field == "condition") {
                    state.areaObj['condition'] = type.val
                    item.binddata = type.val;
                    let typevalue = type.val != null && type.val.includes("A") ? "A" : "D";
                    state.typePoint = item.binddata;
                    if (typevalue == "A") {
                        setTimeout(() => {
                            state.options.tableheads = computed(
                                () => table_headers.hisPointCutSimulateStatistic
                            );
                            state.options.dataUrl = "/hisPointCut/listPointCuts";
                            proxy.$refs.zujianname.getData({});
                        }, 300);
                    } else {
                        setTimeout(() => {
                            state.options.tableheads = computed(
                                () => table_headers.hisPointCutSwitchStatistic
                            );
                            state.options.dataUrl = "/hisPointCut/listPointCuts";
                            proxy.$refs.zujianname.getData({});
                        }, 300);
                    }
                }
            });
            getconditionList(state.areaObj);
        }
        if (type.type == 44) {
            state.options.queryList.querys.forEach((item) => {
                if (item.type == 'cascaderRadioSpecial') {
                    if (item.binddata == '' || !item.binddata) {
                        state.areaObj['areaName'] = type.val1
                        getconditionList(state.areaObj);
                    }
                }
            })
        }
        if (type.type == 5) {
            let dataObj = {
                dateSuffix: undefined,
                classInfo: {},
            };
            state.options.queryList.querys.forEach((item) => {
                if (type.val1) {
                    dataObj.dateSuffix = type.val1
                    if (item.fieldsearch == "banci"&&type.item.type!='datetimestartEnd') {
                        state.banciList.forEach((itemsub) => {
                            if (itemsub.id == item.binddata) {
                                dataObj.classInfo = itemsub;
                                dataObj.typeLabel=2
                                banciList(dataObj);

                            }
                        });
                    }
                } else {
                    if (item.fieldsearch == "datetime") {
                        dataObj.dateSuffix = item.binddata;
                    }
                }
                if (item.fieldsearch == "banci") {
                    state.banciList.forEach((itemsub) => {
                        if (type.val == 0) {
                            type.val = state.banciList[0].id
                        }
                        if (itemsub.id == type.val) {
                            dataObj.classInfo = itemsub;
                            dataObj.typeLabel=2
                            banciList(dataObj);
                        }
                    });
                }
            });
        }
        if (type.type == 'topConnectBom') {
            state.descObj = type.data
            proxy.$refs.zujiannametwo.state.tabledata = []
        }
    }

    function getbanciList() {
        axios.post("/class/info/searchAll", {}).then((res) => {
            state.banciList = res.data.list;
            state.options.queryList.querys.forEach((item) => {
                if (item.fieldsearch == "banci") {
                    item.options = res.data.list.map((item) => {
                        return {
                            label: item.className,
                            value: item.id,
                        };
                    });
                    item.binddata = item.options[0].value
                }
            });
        });
    }
    getbanciList();

    function banciList(dataObj) {
        axios.post("/hisPointFeed/handleClassInfo", dataObj).then((res) => {
            state.options.queryList.querys.forEach((item) => {
                if(dataObj.typeLabel!=2||state.options.queryList.querys[0].binddata==2){
                    if (item.type == "datetimestartEnd") {
                        item.binddata = [res.data.feedStartTime, res.data.feedEndTime];
                    }
                }
            });
        });
    }

    function getassortedCallNamesUrl() {
        return new Promise((resolve, reject) => {
            axios.get(state.assortedCallNamesUrl).then(res => {
                let data = res.data.map(item => {
                    return {
                        label: item,
                        value: item
                    }
                })
                state.options.queryList.querys.forEach(itemsub => {
                    if (itemsub.typesub == 'zuheSpecial') {
                        itemsub.options = data
                    }
                })
                resolve(data)
            })
        })
    }
    getassortedCallNamesUrl()

    function getSelList() {
        axios.post("/hisPointFeed/listAllNames", {
            flag: false
        }).then((res) => {
            state.options.queryList.querys.forEach((item) => {
                if (item.field == "condition") {
                    item.options = res.data;
                }
            });
        });
        searchareaTree().then((res) => {
            state.options.queryList.querys.forEach((item) => {
                if (item.field == "area") {
                    item.options = res.data;
                }
            });
        });
    }

    function getconditionList(val) {
        axios
            .post("/hisPointFeed/conditionList", val)
            .then((res) => {
                state.options.queryList.querys.forEach((item) => {
                    if (item.type == "cascaderRadioSpecial") {
                        item.options = res.data;
                    }
                });
            });
    }
    getconditionList(state.areaObj)
    getSelList();
    onMounted(() => {
        if (router.currentRoute.value.query.label == '组合累积计时') {
            state.options.queryList.querys.forEach(item => {
                if (item.field == 'assortedCallName') {
                    item.title = '组合累积计时名称'
                }
            })
        }
        if (router.currentRoute.value.query.label) {
            state.topTabList.forEach(item => {
                if (item.label == router.currentRoute.value.query.label) {
                    state.options.tableheads = computed(() => table_headers[item.tableheads])
                    state.optionstwo.tableheads = computed(() => table_headers[item.tableheadsT])
                    state.options.dataUrl = item.dataUrl
                    state.optionstwo.dataUrl = item.dataUrlT
                    state.modifyayaUrl = item.modifyayaUrl
                    state.assortedCallNamesUrl = item.assortedCallNamesUrl
                    state.torealUrl = item.torealUrl
                    getassortedCallNamesUrl()
                    proxy.$refs['zujianname'].getData()
                }
            })
        }
    });
    // 跳转实时断电异常页面
    const goPage = () => {
        router.push({
            path: state.torealUrl
        });
    };
    // 关闭曲线
    const closeChart = () => {
        state.listBtnType = undefined
        state.showChart = false
    }
</script>
<style lang="scss" scoped>
    .xiazai {
        position: absolute;
        top: 42px;
        right: 110px;
        width: 120px;
        height: 64px;
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: space-between;
        background-color: #ffff;
        box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
        border-radius: 2px;
        z-index: 99;

        .item {
            width: 100%;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        .item:hover {
            background-color: #ececec;
        }
    }

    ::v-deep .el-drawer {
        .querycss {
            .fsc {
                &:nth-child(2) {
                    display: none;
                }
            }
        }

        .table_box {
            .fsc {
                display: none;
            }
        }
    }
</style>